package code1.double_pointer;

/**
 * 原题链接：https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
 */
public class P0207 {

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lengthA=0,lengthB=0;
        ListNode pa=headA;
        ListNode pb=headB;
        while(pa!=null){
            pa=pa.next;
            lengthA++;
        }
        while(pb!=null){
            pb=pb.next;
            lengthB++;
        }
        pa=headA;
        pb=headB;
        if(lengthA>lengthB){
            for(int i=0;i<lengthA-lengthB;i++){
                pa=pa.next;
            }
        }else{
            for(int i=0;i<lengthB-lengthA;i++){
                pb=pb.next;
            }
        }
        while (pa!=null && pb!=null){
            if(pa==pb){
                return pa;
            }
            pa=pa.next;
            pb=pb.next;
        }
        return null;
    }
}
